let Emitter = require('events').EventEmitter
let util = require('util')

class Tasks {
  constructor() {
    this.queue = []
    this.i = 0
  }
  next(err, ...args) {
    if (!err) {
      let task = this.queue[this.i]
      if (task) {
        ++this.i
        task.apply(null, [(...args) => this.next.apply(this, args)].concat(args))
      } else {
        this.emit('done')
      }
    } else {
      this.emit('error', err)
    }
    return this
  }
  then(task) {
    this.queue.push(task)
    return this
  }
}

util.inherits(Tasks, Emitter)

module.exports = Tasks
